public class Solution {
    public static void main(String[] args) {
        int[][] grid = {{1,3,1},{1,5,1},{4,2,1}};
        System.out.println("最小路径和："+minPathSum(grid));
        int[][] dungeon = {{-2,-3,3},{-5,-10,1},{10,30,-5}};
        System.out.println("地下城游戏: "+calculateMinimumHP(dungeon));
    }
    /*最小路径和*/
    public static int minPathSum(int[][] grid) {
        int m = grid.length;
        int n = grid[0].length;
        int[][] dp = new int[m+1][n+1];
        for (int i = 0; i <= n; i++) {
            dp[0][i] = Integer.MAX_VALUE;
        }
        for (int i = 0; i <= m; i++) {
            dp[i][0] = Integer.MAX_VALUE;
        }
        dp[0][1] = dp[0][1] = 0;
        for (int i = 1; i <= m; i++) {
            for (int j = 1; j <= n; j++) {
                dp[i][j] = Math.min(dp[i-1][j],dp[i][j-1]) + grid[i-1][j-1];
            }
        }
        return dp[m][n];
    }
    /*地下城游戏*/
    public static int calculateMinimumHP(int[][] dungeon) {
        int m = dungeon.length;
        int n = dungeon[0].length;
        int[][] dp = new int[m+1][n+1];
        for (int i = 0; i < n; i++) {
            dp[m][i]  =  Integer.MAX_VALUE;
        }
        for (int i = 0; i < m; i++) {
            dp[i][m]  = Integer.MAX_VALUE;
        }
        //临界条件只剩1滴血
        dp[m][n-1] =  dp[m-1][n] = 1;
        for (int i = m-1; i >=0 ; i--) {
            for (int j = n-1; j >=0 ; j--) {
                dp[i][j] = Math.min(dp[i][j+1],dp[i+1][j]) - dungeon[i][j];
                dp[i][j] = Math.max(1,dp[i][j]);
            }
        }
        return dp[0][0];
    }
    /*奇偶排序数组*/
    public int[] sortArrayByParity(int[] nums) {
        int left = 0;
        int right = nums.length-1;
        while(left < right) {
            while(left < right && nums[left] % 2 == 0) {
                left++;
            }
            while(left < right && nums[right] %2 != 0) {
                right--;
            }
            int tmp = nums[right];
            nums[right] = nums[left];
            nums[left] = tmp;
        }
        return nums;
    }
}
